package com.hdsx.netty.rpcserver.netty;

import com.hdsx.netty.rpcserver.netty.handler.NettyServerInboundHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.net.InetSocketAddress;

/**
 * @author 占贤银
 * time 2024/8/13 23:26
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class RpcRegsitry {

    private int port;

    public RpcRegsitry(int port) {
        this.port = port;
    }


    public static void main(String[] args) {
        new RpcRegsitry(8080).start();
    }

    public void start() {
        EventLoopGroup bossGroup = null;
        EventLoopGroup workerGroup = null;
        try {
            bossGroup = new NioEventLoopGroup();
            workerGroup = new NioEventLoopGroup();
            ServerBootstrap server = new ServerBootstrap();
            // 1、todo bossGroup 主要负责处理吗接收客户端的连接 workerGroup主要负责处理业务逻辑数据
            server.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel)
                                throws Exception {
                            // todo 获取一个管道  在这里添加编解码器
                            ChannelPipeline pipeline = channel.pipeline();
                            // 添加几个Netty自带的自定义协议编解码器
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                            pipeline.addLast(new LengthFieldPrepender(4));
                            pipeline.addLast(new ObjectEncoder());
                            pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                            pipeline.addLast(new NettyServerInboundHandler());
                        }
                        // 获取线程数量
                    }).option(ChannelOption.SO_BACKLOG, 128)
                    // 保持长连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            System.out.println("基于Netty构建的RPC服务已启动，监听端口：" + this.port);
            // 绑定端口号并且同步等待
            ChannelFuture channelFuture = server.bind(new InetSocketAddress(this.port)).sync();
            // 关闭channel
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
